package cn.sc.summer.mybatis.config.tableconfig;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.sc.summer.mybatis.config.superconfig.PackageConfig;
import cn.sc.summer.mybatis.constant.TableConstant;
import cn.sc.summer.mybatis.constant.TableResource;
import cn.sc.summer.mybatis.strategy.basestage.TableInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 类名：建表配置
 *
 * @author a-xin
 * @date 2024/8/27 16:27
 */
@Slf4j
@Configuration
public class TableInfoConfig extends PackageConfig {

    @Bean(name = TableConstant.TABLE_CONFIG_BEAN)
    @ConditionalOnBean(name = {TableConstant.TABLE_CHARSET_BEAN})
    public Boolean tableInfoService() {
        if (CollUtil.isNotEmpty(TableResource.ALL_DATASOURCE_INFO)) {
            Map<String, TableInfoService> tableInfoServiceMap = SpringUtil.getBeansOfType(TableInfoService.class);
            if (CollUtil.isEmpty(tableInfoServiceMap)) {
                throw new IllegalArgumentException("Please set the data source information parsing class!");
            }
            Set<String> dataSourceTypeName = TableResource.ALL_DATASOURCE_INFO.stream().map(item -> item.getDataSourceTypeName().toLowerCase())
                    .collect(Collectors.toSet());
            tableInfoServiceMap.forEach((key, tableInfoService) -> {
                String lowerCase = tableInfoService.getSupports();
                if (CharSequenceUtil.isNotBlank(lowerCase) && dataSourceTypeName.contains(lowerCase)) {
                    TableResource.TABLE_CONFIG_INFO.put(lowerCase, tableInfoService);
                }
            });
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}
